<template>
  <div>
    <el-upload
      style="width: 500px;"
      :headers="headers"
      :action="uploadPath"
      list-type="picture-card"
      :file-list="links"
      :on-success="uploadUrl"
      :before-upload="checkFileSize"
      :accept="accept"
    >
      <i slot="default" class="el-icon-plus" />
      <div slot="file" slot-scope="{file}" style="height: 100%">
        <img v-if="!endWith(file.url,'.mp4')" class="el-upload-list__item-thumbnail" :src="file.url">
        <video v-else :id="'video-'+file.url" controls="controls" style="height: 85%" class="el-upload-list__item-thumbnail" preload="metadata">
          <source :src="file.url" type="video/mp4">
        </video>
        <!--              <img v-if="endWith(file.url,'.mp4')" class="el-upload-list__item-thumbnail" :src="getVideoFirstImg(file.url)">-->
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in" />
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
      <div slot="tip" class="el-upload__tip">只能上传{{ accept.replace(/\./g,'') }}文件，且不超过35M</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img v-if="!endWith(dialogImageUrl,'.mp4')" style="width: 100%" :src="dialogImageUrl" alt="">
      <video v-else width="100%" controls>
        <source :src="dialogImageUrl" type="video/mp4">
      </video>
    </el-dialog>
  </div>
</template>

<script>
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
export default {
  name: 'Upload',
  props: { links: {
    type: Array,
    required: true
  }, accept: {
    type: String,
    required: true
  }},
  data() {
    return {
      uploadPath,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },
  computed: {
    headers() {
      return {
        'mbl_token': getToken()
      }
    }
  },
  methods: {
    uploadUrl: function(response) {
      this.links.push({
        url: response.data.url
      })
    },
    checkFileSize: function(file) {
      if (file.size > 1048576 * 35) {
        this.$message.error(`${file.name}文件大于35M，请选择小于35M大小的图片`)
        return false
      }
      return true
    },
    endWith(str, endStr) {
      const d = str.length - endStr.length
      return (d >= 0 && str.lastIndexOf(endStr) === d)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file) {
      for (let i = 0; i < this.links.length; i++) {
        if (file.url == this.links[i].url) {
          this.links.splice(i, 1)
          return
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
